<template>
	<div class="recharge-container">
	    <form>
			<div class="form-group">
				<label>充值金额:</label>
				<input type="text" id="account" v-model="account" required placeholder=" 请输入充值金额......">
			</div>
			<button type="submit" @click="recharge()">充值</button>
	    </form>
		<text class="tips">(只可充值正整数金额)</text>
	</div>
	
</template>

<script>
	import request from '../../utils/request.js';
	import Vue from 'vue'
	
	export default {
		data() {
			return {
				userInfo:{},
				account:null,
				allUserInfo:[]
			};
		},
		computed: {
			
		},
		mounted(){
			this.getAllUserInfo();
			wx.getStorage({
				key:'userInfo',
				success:(res)=>{
					this.userInfo=JSON.parse(res.data);
				}
			});
		},
		methods: {
			async getAllUserInfo(){
				const res=await request('/getUserInfo');
				this.allUserInfo=res.userInfo;
			},
			recharge(){
				this.account=Number(this.account);
				if(Math.sign(this.account)===1&&Number.isInteger(this.account)){
					console.log(this.userInfo.nickName+'充值'+this.account+'元');
					//修改数据库
					var newBalance=this.userInfo.balance+this.account;
					request('/recharge?account='+newBalance+'&nickName='+this.userInfo.nickName);
					this.getAllUserInfo();
					var that=this;
					wx.showModal({
						title:'提示',
						content:'充值成功!',
						success(res){
							if(res.confirm){
								that.refresh();
								wx.reLaunch({
									url:'/pages/personal/personal'
								})
							}
						}
					})
				}else{
					wx.showModal({
						title:'提示',
						content:'请输入合法数值!',
						success(res){
							if(res.confirm){
								wx.reLaunch({
									url:'/pages/recharge/recharges'
								})
							}
						}
					})
				}
			},
			refresh(){
				//修改Storage
				var that=this;
				var i,index;
				var flag=false;
				for(i=0;i<this.allUserInfo.length;i++){
					if(this.userInfo.nickName===this.allUserInfo[i].nickName){
						flag=true;
						index=i;
						break;
					}
				}
				wx.setStorage({
					key:"userInfo",
					data:JSON.stringify(that.allUserInfo[index])
				})
			}
		}
	}
</script>

<style scoped>
	.recharge-container {
		margin: 150rpx auto;
		padding: 20px;
	}
	.form-group {
		margin-bottom: 15px;
		display: flex;
		align-items: center;
	}	
	label {
		width: 150rpx;
		text-align: center;
		font-size: 35rpx;
		margin-right: 5px;
	}
	input {
		width: 80%;
		height: 90rpx;
		line-height: 90rpx;
		box-sizing: border-box;
		border: 1px solid #000;
		border-radius: 5px;
	}
	button {
		margin-top: 100rpx;
		width: 80%;
		height: 100rpx;
		background-color: #bb2c08;
		color: white;
		border: none;
		border-radius: 5px;
	}
	.tips{
		position: absolute;
		margin-top: 50rpx;
		margin-left: 160rpx;
	}
</style>